import React, { useMemo, useState, useEffect } from 'react';
import { Button, Drawer, Form, Select, Input, Table, Divider, InputNumber, Tooltip, Slider, message } from 'antd';
import wrapper from '@utils/wrapper';
import { QuestionCircleOutlined } from '@ant-design/icons'
import { ServerRecord } from '../index';
import { APIRecord } from '../../api_import/index';
import { apiTypes } from '../../mock';
import api from '@request/api_import';
import serverApi from '@request/server_manage';
import Icon from '@components/icon';
import createApiModal from '../../api_import/create_api_modal/index';

interface CreateServerModalProps {
  type: 'add' | 'edit' | 'view',
  record: ServerRecord,
  visible: boolean,
  closeDialog: () => void,
  getList: () => void,
}
interface AddServerParams {
  name: string,
  id?: number,
  type: string,
  desc?: string,
  api_infos: { id: number, name: string, weight: number }[]
}
const actionType = {
  add: '新建',
  edit: '编辑',
  view: '查看'
}
const layout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 20,
  },
}
const Option = Select.Option;
const CreateServerModal = (props: CreateServerModalProps) => {
  const {
    type: OpenModlaType,
    record,
    visible,
    closeDialog,
    getList
  } = props;
  const [addApiData, setApiData] = useState<any>([]);
  const [type, setType] = useState<string | undefined>();// 服务类型
  const [apiList, setApiList] = useState<APIRecord[] | []>([]); // 筛选type之后的api列表
  const [originApiList, setOriginApiList] = useState<APIRecord[] | []>([]); // 全量api列表
  const [form] = Form.useForm();
  const { getFieldValue, validateFields, setFieldsValue } = form;
  const disabled = OpenModlaType === 'view' ? true : false;
  useEffect(() => {
    if (['view', 'edit'].includes(OpenModlaType)) {
      setFieldsValue({
        name: record.name,
        desc: record.desc,
        type: record.type
      })
      setApiData(() => {
        let newState = record.api_infos.map(item => {
          return {
            ...item,
            uuid: Math.random() // 开始默认给一个uuid
          }
        })
        return newState
      })
    }
  }, [])
  useEffect(() => {
    api.getApiList()
      .then(res => {
        setOriginApiList(res.data);
        // 初始化的时候，根据type设置api table里面的apiList数据
        if (['edit', 'add'].includes(OpenModlaType)) {
          setApiList(() => {
            return res.data.filter((item: APIRecord) => item.type === record.type);
          })
        }
      })
  }, []);

  const addApi = () => {
    let obj = {
      uuid: Math.random(),
      name: '',
      weight: '',
    }
    setApiData((pre: any[]) => {
      return [
        ...pre,
        obj
      ]
    })
  }
  const deleteApi = (record: { uuid: any; }) => {
    setApiData((pre: any[]) => {
      return pre.filter(item => item.uuid !== record.uuid);
    })
  }
  // 切换服务类型
  const changeServerType = async (value: string) => {
    setType(value);
    setApiList(() => {
      let newState = originApiList.filter(item => item.type === value);
      return [...newState]
    })
    setApiData([]);
  }
  // 改变权重
  const changeWeight = (value: number, uuid: number) => {
    setApiData((pre: any[]) => {
      pre.forEach(item => {
        if (item.uuid === uuid) item.weight = value
      })
      return [...pre]
    })
  }
  // 选择api
  const changeApi = (
    { value, label }: { key: number, label: string, value: number },
    record: { uuid: any; }
  ) => {
    setApiData((pre: any[]) => {
      pre.forEach(item => {
        if (item.uuid === record.uuid) {
          item.name = label;
          item.id = value
        }
      })
      return [...pre]
    })
  }
  const columns = useMemo(() => {
    return [
      {
        title: 'API选择',
        dataIndex: 'name',
        render: (text: string, record: any) => {
          return <Select
            labelInValue
            disabled={disabled}
            style={{ width: '200px' }}
            onChange={(value: any) => changeApi(value, record)}
            value={{ value: text }}
          >
            {
              apiList.map(item => {
                return <Option key={item.id} value={item.id}>{item.name}</Option>
              })
            }
          </Select>
        }
      },
      {
        title: <span>权重分配（%）<Tooltip placement='top' title='权重分配总和必须为100%'><QuestionCircleOutlined /></Tooltip></span>,
        dataIndex: 'weight',
        width: '250px',
        render: (text: number, record) => {
          return <div style={{display: 'flex'}}>
            <Slider style={{width: '120px'}} min={1} max={100} disabled={disabled} onChange={(value) => changeWeight(value, record.uuid)} value={text} />
            <InputNumber style={{width: '90px'}} max={100} min={1} disabled={disabled} addonAfter={'%'} onChange={(value) => changeWeight(value, record.uuid)} value={text} />
          </div>
        }
      },
      {
        title: '操作',
        dataIndex: 'action',
        render: (_text: string, record) => {
          return (
            <>
              <a onClick={() => openApiModal(record)}>查看</a>
              <Divider type="vertical" />
              <a disabled={disabled} onClick={disabled ? () => { } : () => deleteApi(record)}>删除</a>
            </>
          )
        }
      }
    ]
  }, [addApiData, apiList]);
  const openApiModal = (record) => {
    api.getApiInfoById({
      query: {
        id: record.id
      }
    })
      .then(apiInfo => {
        createApiModal({
          type: 'view',
          record: apiInfo
        })
      })
  }
  const checkData = (addApiData: any) => {
    if(addApiData.length === 1) return true; // 如果只有一条数据，默认是百分之百
    let sum = 0;
    sum = addApiData.reduce((pre: number, cur: any) => {
      return pre + cur.weight;
    }, 0);

    return sum === 100 ? true : false;
  }
  const onOk = () => {
    if (OpenModlaType === 'view') return closeDialog && closeDialog();
    validateFields()
      .then(async info => {
        if(!checkData(addApiData)) {
          message.error('api权重总和必须为100%')
          return;
        }
        let params: AddServerParams = {
          ...info,
          api_infos: addApiData
        }
        if (OpenModlaType === 'add') {
          await serverApi.createServer({
            body: params
          })
        } else {
          await serverApi.updateServer({
            body: {
              ...params,
              id: record.id
            }
          })
        }
        closeDialog && closeDialog();
        getList && getList();
      })
  }

  const title = actionType[OpenModlaType] + '服务';
  return <Drawer
    visible={visible}
    title={title}
    closable={false}
    width={650}
    footer={
      <>
        <Button style={{ float: 'right', marginLeft: '12px' }} type='primary' onClick={onOk}>确定</Button>
        <Button style={{ float: 'right' }} onClick={closeDialog}>取消</Button>
      </>
    }
    onClose={closeDialog}
  >
    <Form form={form} {...layout}>
      <Form.Item name='name' label='服务名称' rules={[{ required: true, message: '请输入应用名称' }]}>
        <Input disabled={disabled} placeholder='请输入服务名称' />
      </Form.Item>
      <Form.Item name='desc' label='服务描述'>
        <Input.TextArea disabled={disabled} rows={2} />
      </Form.Item>
      <Form.Item name='type' label='服务类型'>
        <Select disabled={disabled} onChange={changeServerType} value={type}>
          {
            apiTypes.map(item => {
              return <Option key={item.key} value={item.key}>{item.name}</Option>
            })
          }
        </Select>
      </Form.Item>
    </Form>
    {
      ['edit', 'add'].includes(OpenModlaType) && <Button onClick={addApi} style={{ marginBottom: '12px' }}>添加API</Button>
    }
    <Table
      columns={columns}
      dataSource={addApiData}
      pagination={false}
    />
  </Drawer>
}

export default wrapper(CreateServerModal);